package net.wendal.luat.errdump;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Files;
import org.nutz.lang.Streams;
import org.nutz.log.Log;
import org.nutz.log.Logs;

@IocBean
public class ErrDumpServer extends Thread {

    private static final Log log = Logs.get();

    @Inject
    protected PropertiesProxy conf;

    protected ExecutorService es;

    public ErrDumpServer() {
        setDaemon(false);
        setName("errDump");
        es = Executors.newCachedThreadPool();
    }

    @Override
    public void run() {
        ServerSocket ss = null;
        try {
            ss = new ServerSocket(conf.getInt("server.port", 9072));
            String dstDir = conf.get("errDump.dir", "/data/errDump/");
            while (true) {
                Socket socket = ss.accept();
                es.submit(new Runnable() {
                    public void run() {
                        try {
                            byte[] buf = Streams.readBytes(socket.getInputStream());
                            if (buf.length > 0) {
                                Files.write(Files.createFileIfNoExists(dstDir + System.currentTimeMillis() + ".data"), buf);
                            }
                        }
                        catch (Throwable e) {
                            log.debug("something happen", e);
                        }
                        finally {
                            Streams.safeClose(socket);
                        }
                    }
                });
            }
        }
        catch (Throwable e) {
            log.error("!!!!listen ERROR!!!!!", e);
            System.exit(1);
        }
        finally {
            Streams.safeClose(ss);
        }
    }
}
